﻿using CCWin;
using ERP_SaaS_WinForm.登录.Model;
using ERP_SaaS_WinForm.销售;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace ERP_SaaS_WinForm.登录
{
    public partial class ShowProductInspections : CCSkinMain
    {
        public ShowProductInspections()
        {
            InitializeComponent();
            cmpagesize.SelectedIndex = 0; // 默认选择每页显示15条
            LoadPageData();
            this.Load += ShowProductInspections_Load;
        }
        public HttpClient client = new HttpClient();
        private int currentPage = 1; // 当前页码
        private int pageSize = 999; // 默认每页行数

        private int totalPages; // 总页数
        private string apiUrl = "http://10.223.8.3:8077/api/ProductIntory/ShowProductsInspection"; // API地址
        private  void   PageInspections_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (PageInspections.Columns[e.ColumnIndex] is DataGridViewButtonColumn)
            {
                string columnName = PageInspections.Columns[e.ColumnIndex].Name;

                // 获取当前行的数据
                int rowIndex = e.RowIndex;
                DataGridViewRow row = PageInspections.Rows[rowIndex];

                // 处理编辑操作
                if (columnName == "editbtn")
                {
                    //确认是否编辑
                    DialogResult result = MessageBox.Show("确定要编辑该记录吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        var procurementForm = new ERP_SaaS_WinForm.登录.UpdateProductInspact();
                        procurementForm.id=int.Parse(row.Cells["ProductsInspection_Id"].Value.ToString());
                        procurementForm.Show();
                    }

                }
                else if (columnName == "deletebtn")
                {
                    //确认是否编辑
                    DialogResult result = MessageBox.Show("确定要删除该记录吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        ///获取当前行的id
                        int id = int.Parse(row.Cells["ProductsInspection_Id"].Value.ToString());
                         DelData(id);
                    }
                }
            }
        }
        private string apidel = "http://10.223.8.3:8077/api/ProductIntory/DeleteProductsInspection";
        public async Task<int> DelData(int id)
        {

            //构建API请求
            string requestUrl = $"{apidel}?id={id}";
            HttpResponseMessage response = await client.GetAsync(requestUrl);
            if (response.IsSuccessStatusCode)
            {
                MessageBox.Show("删除成功！");
                LoadPageData();
                return 1;
            }
            else
            {
                MessageBox.Show("删除失败！");
                return 0;
            }
        }

        private async void LoadPageData()
        {
            try
            {
                // 构建API请求（含分页参数）
                string requestUrl = $"{apiUrl}?currentpage={currentPage}&pagesize={cmpagesize.Text}";
                HttpResponseMessage response = await client.GetAsync(requestUrl);
                string json = await response.Content.ReadAsStringAsync();

                // 反序列化为ApiPaging<T>（假设T是List<YourModel>）
                var apiPaging = JsonConvert.DeserializeObject<ApiPaging<List<ProductInspection>>>(json);
                // 绑定数据到DataGridView
                PageInspections.DataSource = apiPaging.data;
                // 更新分页信息显示
                lblMassage.Text = $"第{apiPaging.currentpage}页/共{apiPaging.totalpages}页 (总记录: {apiPaging.totalcount})";
                totalPages = apiPaging.totalpages;

            }
            catch (Exception ex)
            {
                MessageBox.Show($"API调用失败: {ex.Message}");
            }

        }
        private void btnselect_Click(object sender, EventArgs e)
        {

        }

        private void ShowProductInspections_Load(object sender, EventArgs e)
        {

        }

        private void dtnget_Click(object sender, EventArgs e)
        {
            LoadPageData();
        }
        /// <summary>
        /// 点击第一页按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtfirst_Click(object sender, EventArgs e)
        {
            currentPage = 1;
            LoadPageData();
        }
        /// <summary>
        /// 点击最后一页按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void txtlast_Click(object sender, EventArgs e)
        {
            currentPage = totalPages;
            LoadPageData();
        }

        // 分页按钮点击事件
        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (currentPage > 1)
            {
                currentPage--;
                LoadPageData();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (currentPage < totalPages)
            {
                currentPage++;
                LoadPageData();
            }
        }

        private void cmpagesize_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadPageData();
        }

        private void txtadd_Click(object sender, EventArgs e)
        {
            var procurementForm = new ERP_SaaS_WinForm.登录.UpdateProductInspact();
            procurementForm.btn = "添加";
            procurementForm.Show();
        }
    }
}
